from django.db import models
from django.contrib.auth.models import User


class AIModel(models.Model):
    """AI模型配置"""
    MODEL_TYPES = [
        ('openai', 'OpenAI'),
        ('claude', 'Claude'),
        ('local', '本地模型'),
        ('custom', '自定义模型'),
    ]
    
    name = models.CharField('模型名称', max_length=100, unique=True)
    description = models.TextField('模型描述', blank=True)
    model_type = models.CharField('模型类型', max_length=20, choices=MODEL_TYPES, default='openai')
    api_endpoint = models.URLField('API端点', blank=True, help_text='API服务的URL地址')
    api_key = models.CharField('API密钥', max_length=200, blank=True, help_text='用于认证的API密钥')
    max_tokens = models.IntegerField('最大Token数', default=2048, help_text='单次对话最大Token数量')
    temperature = models.FloatField('温度参数', default=0.7, help_text='控制回复的随机性，0-1之间')
    is_active = models.BooleanField('是否激活', default=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        verbose_name = 'AI模型'
        verbose_name_plural = 'AI模型'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.name} ({self.get_model_type_display()})"


class ChatSession(models.Model):
    """聊天会话模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户', null=True, blank=True)
    session_id = models.CharField('会话ID', max_length=100, unique=True)
    title = models.CharField('会话标题', max_length=200, default='新对话')
    ai_model = models.ForeignKey(AIModel, on_delete=models.SET_NULL, null=True, verbose_name='使用的AI模型')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    is_active = models.BooleanField('是否活跃', default=True)
    
    class Meta:
        verbose_name = '聊天会话'
        verbose_name_plural = '聊天会话'
        ordering = ['-updated_at']
        
    def __str__(self):
        return f"{self.title} - {self.created_at.strftime('%Y-%m-%d %H:%M')}"
    
    @property
    def message_count(self):
        return self.messages.count()


class ChatMessage(models.Model):
    """聊天消息模型"""
    ROLE_CHOICES = [
        ('user', '用户'),
        ('assistant', 'AI助手'),
        ('system', '系统'),
    ]
    
    session = models.ForeignKey(ChatSession, on_delete=models.CASCADE, related_name='messages', verbose_name='所属会话')
    role = models.CharField('角色', max_length=10, choices=ROLE_CHOICES)
    content = models.TextField('消息内容')
    tokens_used = models.IntegerField('使用Token数', default=0, help_text='此消息使用的Token数量')
    timestamp = models.DateTimeField('时间戳', auto_now_add=True)
    
    class Meta:
        verbose_name = '聊天消息'
        verbose_name_plural = '聊天消息'
        ordering = ['timestamp']
        
    def __str__(self):
        return f"{self.get_role_display()}: {self.content[:50]}..."


class AIPromptTemplate(models.Model):
    """AI提示词模板"""
    name = models.CharField('模板名称', max_length=100, unique=True)
    description = models.TextField('模板描述', blank=True)
    system_prompt = models.TextField('系统提示词', help_text='定义AI的角色和行为')
    user_prompt_template = models.TextField('用户提示词模板', blank=True, help_text='用户输入的模板，支持变量')
    is_default = models.BooleanField('是否为默认模板', default=False)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    
    class Meta:
        verbose_name = 'AI提示词模板'
        verbose_name_plural = 'AI提示词模板'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name
    
    def save(self, *args, **kwargs):
        # 确保只有一个默认模板
        if self.is_default:
            AIPromptTemplate.objects.filter(is_default=True).update(is_default=False)
        super().save(*args, **kwargs)


class APIUsageLog(models.Model):
    """API使用日志"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户', null=True, blank=True)
    ai_model = models.ForeignKey(AIModel, on_delete=models.CASCADE, verbose_name='AI模型')
    session = models.ForeignKey(ChatSession, on_delete=models.CASCADE, verbose_name='会话', null=True, blank=True)
    request_content = models.TextField('请求内容')
    response_content = models.TextField('响应内容')
    tokens_used = models.IntegerField('使用Token数', default=0)
    response_time = models.FloatField('响应时间(秒)', default=0.0)
    status = models.CharField('状态', max_length=20, default='success', choices=[
        ('success', '成功'),
        ('error', '错误'),
        ('timeout', '超时'),
    ])
    error_message = models.TextField('错误信息', blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    
    class Meta:
        verbose_name = 'API使用日志'
        verbose_name_plural = 'API使用日志'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.ai_model.name} - {self.created_at.strftime('%Y-%m-%d %H:%M:%S')}"


class UserPreference(models.Model):
    """用户偏好设置"""
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='用户')
    preferred_ai_model = models.ForeignKey(AIModel, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='偏好AI模型')
    default_temperature = models.FloatField('默认温度参数', default=0.7)
    default_max_tokens = models.IntegerField('默认最大Token数', default=2048)
    auto_save_history = models.BooleanField('自动保存历史', default=True)
    theme = models.CharField('主题', max_length=20, default='light', choices=[
        ('light', '浅色'),
        ('dark', '深色'),
    ])
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    class Meta:
        verbose_name = '用户偏好'
        verbose_name_plural = '用户偏好'
    
    def __str__(self):
        return f"{self.user.username}的偏好设置"
